import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { InputNumber, message } from 'antd';
import 'moment/locale/zh-cn';
import { TableC, SecondHeaderC, PrimaryGhostC } from '../../.././../../../comps';
import myStyle from '../../index.less';
import colors from '../../../../../../css/colors';
import config from '../../.././../../../comps/business/tradingMarket/config';
import moment from 'moment';
@connect(({ optimizationM, workStationM, loading }) => ({
  optimizationM,
  workStationM,
  loading,
}))
@Form.create()
export default class FormTableC extends PureComponent {
  state = {
    totalRow: { order: '总计', initWeight: 0 }, //总计行
    errorMsg: '', //错误提示消息
    dataSource: [],
    date: undefined, //持仓日期
  };

  componentDidMount() {
    this.props.onRef(this);
  }
  //获取持仓列表
  getHoldList = (date) => {
    if (!date) {
      this.setState({
        dataSource: [],
      });
      return;
    }
    date = moment(date).format('YYYY-MM-DD');
    this.setState({
      date, //持仓日期
      errorMsg: '',
      dataSource: [],
    });
    if (this.props.portfolioType == '1') {
      //真实
      this.queryHoldRealData(date);
    } else {
      this.queryHoldVirtualData(date);
    }
  };

  //计算权重之和
  calcWeight = (arr = []) => {
    let sum = 0;
    arr.map((item, index) => {
      if (index != arr.length - 1) {
        sum = sum + (item.initWeight * 1 || 0);
      }
    });
    arr[arr.length - 1].initWeight = sum;
  };

  //校验每行数据
  checkObj = (arr, obj) => {
    for (var i = 0; i < arr.length; i++) {
      let key = arr[i];
      if (obj[key] !== 0 && !obj[key]) {
        this.setState({
          errorMsg: '请设置完整的条件!',
        });
        return key;
      }
    }
    return null;
  };

  //表格提交
  submit = () => {
    const { dataSource } = this.state;
    const { initColumns, portfolioType } = this.props;
    var msg = '';
    var columnKeys = [];
    initColumns.map((item) => {
      //选中的column对应的key
      if (item.isNeed) {
        columnKeys.push(item.key);
      }
    });

    if (dataSource.length < 2) {
      //真实不参与
      msg = '无持仓设置表格数据,可通过时间区间和组合下拉的调整来获取!';
      this.setState({
        errorMsg: msg,
      });
      return null;
    }
    for (var i = 0; i < dataSource.length; i++) {
      var item = dataSource[i];
      item.isRed = false;
      if (item.order != '总计') {
        var index = this.checkObj(columnKeys, item);
        if (index) {
          item.isRed = true;
          this.setState({
            dataSource: [...dataSource],
          });
          return null;
        }
        if (item.weightBottom && item.weightTop &&columnKeys.includes("weightTop")) {
          if (item.weightBottom > item.weightTop || item.weightBottom == item.weightTop) {
            msg = '权重上界必须大于权重下界';
            this.setState({
              errorMsg: msg,
            });
            item.isRed = true;
            this.setState({
              dataSource: [...dataSource],
            });
            return null;
          }
        }
      } else if (portfolioType != 1 && !(Number(item.initWeight.toFixed(2)) > 0.9999 && Number(item.initWeight.toFixed(2) < 1.0001))) {
        console.log(item, '模拟需要校验');
        msg = '总权重不等于100%，请调整或进行归一化处理';
        this.setState({
          errorMsg: msg,
        });
        return null;
      }
    }

    this.setState({
      errorMsg: '',
    });
    return dataSource;
  };

  //父组件点击重置按钮
  reset = () => {
    this.setState({
      dataSource: [],
      errorMsg: '', //错误提示消息
    });
  };

  //归一化处理
  setWeight = () => {
    const { dataSource, totalRow } = this.state;
    if (dataSource.length < 2) return; //没有新增不进行计算
    dataSource.map((item, index) => {
      var sum = dataSource[dataSource.length - 1].initWeight;
      console.log(sum);
      if (index != dataSource.length - 1) {
        item.initWeight = sum === 0 ? undefined : parseFloat((item.initWeight || 0) / sum) * 1;
      } else {
        item.initWeight = sum == 0 ? 0 : 1;
      }
    });
    this.setState({
      errorMsg: this.state.errorMsg == '总权重不等于100%，请调整或进行归一化处理' ? '' : this.state.errorMsg,
      dataSource: [...dataSource],
    });
  };
  //初始化表格
  initTable = () => {
    const { initColumns, typeStatus } = this.props;
    const { dataSource, errorMsg } = this.state;
    let columns = initColumns.filter((item) => item.isNeed == true); //过滤需要展示的列
    columns.map((item) => {
      if (item.key != 'order' || item.key != 'operate') {
        if (item.key != 'asset' && typeStatus != '3') item.width = parseFloat(90 / columns.length) - 1 + '%'; //设置宽度
        if (item.key == 'asset') {
          item.align = 'right';
          item.render = (text, record) => {
            //设置展示的form表单 资产
            if (record.order == '总计') return text; //总计行展示
            return record?.title;
          };
        } else if (item.key == 'initWeight') {
          item.render = (text, record) => {
            //设置展示的form表单
            if (record.order == '总计') {
              //总计行展示
              return (text * 100).toFixed(2) + '%';
            }
            return (text * 100).toFixed(2);
          };
        } else {
          item.render = (text, record) => {
            //设置展示的form表单
            if (record.order == '总计') {
              //总计行展示
              return text;
            }
            return typeStatus != '3' ? (
              <InputNumber
                value={record[item.key]}
                className={errorMsg && record.isRed ? myStyle.hasError : ''}
                min={0}
                max={100}
                step={0.1}
                precision={2}
                placeholder={'请输入0-100的数字'}
                style={{ width: '100%' }}
                onChange={(value) => {
                  var pattern = /^(\+)?\d+(\.\d+)?$/;
                  if (!pattern.test(value)) return; //只允许>0 数字和小数时调用
                  if (value > 100) return;
                  record[item.key] = value;
                  dataSource.map((row) => {
                    if (row.order == record.order) {
                      row = { ...record };
                    }
                  });
                  this.setState({
                    //渲染表格,使修改生效
                    dataSource: [...dataSource],
                  });
                }}
              />
            ) : (
              (text * 1).toFixed(2)
            );
          };
        }
      }
    });
    if (columns && columns.length && columns[columns.length - 1].key != 'operate') {
      columns.unshift({
        key: 'order',
        title: '序号',
        width: 100,
        align: 'center',
        render: (text) => {
          return text < 10 ? `0${text}` : text;
        },
      });
    }
    return (
      <TableC
        columns={columns}
        dataSource={dataSource}
        rowKey='order'
        hidePage={true}
        scroll={{ x: '100%', y: 160 }}
        rowClassName={(record, index) => {
          //设置最后一行样式
          if (dataSource?.length - 1 == index) {
            return myStyle.fixedtr;
          }
        }}
      />
    );
  };
  //查询持仓真实列表
  queryHoldRealData = (date) => {
    const { totalRow } = this.state;
    const { productCode, portfolioId, portfolioType } = this.props;
    // 获取真实获取持仓管理列表
    this.props.dispatch({
      type: 'optimizationM/queryHoldRealData',
      payload: {
        pageSize: 999999,
        page: 1,
        dataDt: moment(date).format('YYYY-MM-DD'),
        timestamp: +new Date(),
        isHkStk: '0',
        searchType: 'pt',
        trdAttr: 'PT',
        type: 'barra',
        fundId: [portfolioId],
      },
      callback: (data) => {
        if (!data) {
          //无数据
          this.setState({
            dataSource: data || [],
          });
          return;
        }
        let dataSource = [];
        data.map((child, key) => {
          //以下代码给证券代码+.SH 类似的标志
          let findvalue = config.filter((item) => {
            return child.id.exchangecode == item.value;
          });
          let text = child.tradingcode;
          if (findvalue && findvalue.length > 0) {
            child.label = text ? text + '.' + findvalue[0].abbr : text;
          } else {
            child.label = text;
          }
          child.title = child.zqName + '-' + child.label;
          //得到表格展示数据
          dataSource.push({
            asset: child.secucode, //资产内码
            initWeight: child.weight, //初始权重
            title: child.title, //展示名称
            order: key + 1, //顺序
          });
        });
        dataSource.push(totalRow);

        //计算权重之和
        this.calcWeight(dataSource);
        this.setState({
          dataSource: [...dataSource] || [],
        });
      },
    });
  };
  // 获取模拟持仓列表
  queryHoldVirtualData = (date) => {
    const { portfolioId } = this.props;
    const { totalRow } = this.state;
    this.props.dispatch({
      type: 'optimizationM/queryHoldVirtualData',
      payload: {
        portfolioId: portfolioId,
        date: date,
      },
      callback: (data) => {
        if (data) {
          let dataSource = [];
          data.map((child, key) => {
            //得到表格展示数据
            dataSource.push({
              asset: child.secucode, //资产内码
              initWeight: child.holdingWeight, //初始权重
              title: child.securitiesName + '-' + child.securitiesCode, //展示名称
              order: key + 1, //顺序
            });
          });
          dataSource.push(totalRow);
          //计算权重之和
          this.calcWeight(dataSource);
          this.setState({
            errorMsg: totalRow.initWeight != 1 ? '总权重不等于100%，请调整或进行归一化处理' : this.state.errorMsg,
            dataSource: [...dataSource] || [],
          });
        } else {
          //无数据
          this.setState({
            dataSource: [],
          });
        }
      },
    });
  };

  render() {
    const { errorMsg, date, dataSource = [] } = this.state;
    const { portfolioType, typeStatus } = this.props;
    return (
      <div className={myStyle.tableForm}>
        <SecondHeaderC
          title='持仓设置'
          Right={`优化前持仓日期：${date || '--'}`}
          Left={
            portfolioType == 1 || typeStatus == 3 ? null : (
              <PrimaryGhostC style={{ marginLeft: '15px' }} title={'归一化'} onClick={this.setWeight} disabled={!dataSource.length}></PrimaryGhostC>
            )
          }
        />
        {this.initTable()}
        {typeStatus != '3' ? (
          <div className='addRow' style={this.props.barraConst == 1 ? { border: 0, paddingLeft: '110px' } : { paddingLeft: '110px' }}>
            <span style={{ display: errorMsg ? 'inherit' : 'none', color: colors.debtAndProfit.text[0] }}>{errorMsg}</span>
          </div>
        ) : null}
      </div>
    );
  }
}
